package kankan.wheel.activity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kankan.wheel.R;
import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

/**
 * @author yxz
 */
public class CitiesActivity extends Activity implements
		OnWheelChangedListener {
	/**
	 * 把全国的省市区的信息以json的格式保存，解析完成后赋值为null
	 */
	/**
	 * 省的WheelView控件
	 */
	private WheelView mProvince;
	/**
	 * 市的WheelView控件d
	 */
	private WheelView mCity;
	/**
	 * 区的WheelView控件
	 */
	private WheelView mArea;
	/**
	 * 所有省
	 */
	private ArrayList<String> mProvinceDatas;
	private ArrayList<String> mProvinceDatasId;
	/**
	 * key - 省 value - 市s
	 */
	private Map<String, ArrayList<String>> mCitisDatasMap = new HashMap();
	private Map<String, ArrayList<String>> mCitisDatasMapId = new HashMap();
	/**
	 * key - 市 values - 区s
	 */
	private Map<String, ArrayList<String>> mAreaDatasMap = new HashMap();
	private Map<String, ArrayList<String>> mAreaDatasMapId = new HashMap();

	/**
	 * 当前省的名称和 id
	 */
	private String mCurrentProviceName;
	private String mCurrentProviceId;
	private int mCurrentProvicePos;
	/**
	 * 当前市的名称和id
	 */
	private String mCurrentCityName;
	private String mCurrentCityId;
	private int mCurrentCityPos;
	/**
	 * 当前区的名称he id
	 */
	private String mCurrentAreaName = "";
	private String mCurrentAreaId = "";
	private int mCurrentAreaPos;

	Map<String, String> paramMap = new HashMap<String, String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.citys);
		mProvince = (WheelView) findViewById(R.id.id_province);
		mCity = (WheelView) findViewById(R.id.id_city);
		mArea = (WheelView) findViewById(R.id.id_area);
		try {
			JSONObject mJsonObj = new JSONObject(initJsonData());
			JSONArray jsonArray = mJsonObj.getJSONArray("location");
			mProvinceDatas = new ArrayList();
			mProvinceDatasId = new ArrayList();

			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonP = jsonArray.getJSONObject(i);// 每个省的json对象
				String province = jsonP.getString("province_name");// 省名字
				String province_id = jsonP.getString("province_id");// 省名字

				mProvinceDatas.add(i, province);
				mProvinceDatasId.add(i, province_id);

				JSONArray jsonCs = jsonP.getJSONArray("city");

				ArrayList mCitiesDatas = new ArrayList();
				ArrayList mCitiesDatasId = new ArrayList();
				for (int j = 0; j < jsonCs.length(); j++) {
					JSONObject jsonCity = jsonCs.getJSONObject(j);
					String city = jsonCity.getString("city_name");// 市名字
					String cityId = jsonCity.getString("city_id");// 市名字
					mCitiesDatas.add(j, city);
					mCitiesDatasId.add(j, cityId);
					JSONArray jsonAreas = jsonCity.getJSONArray("county");
					ArrayList mAreasDatas = new ArrayList();// 当前市的所有区
					ArrayList mAreasDatasId = new ArrayList();// 当前市的所有区
					for (int k = 0; k < jsonAreas.length(); k++) {
						String area = jsonAreas.getJSONObject(k).optString(
								"county_name");// 区域的名称
						String areaId = jsonAreas.getJSONObject(k).optString(
								"county_id");// 区域的名称
						mAreasDatas.add(k, area);
						mAreasDatasId.add(k, areaId);
					}
					mAreaDatasMap.put(city, mAreasDatas);
					mAreaDatasMapId.put(cityId, mAreasDatasId);
				}
				mCitisDatasMap.put(province, mCitiesDatas);
				mCitisDatasMapId.put(province_id, mCitiesDatasId);

			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mProvince.setViewAdapter(new ArrayWheelAdapter<String>(
				CitiesActivity.this, mProvinceDatas));
		// 添加change事件
		mProvince.addChangingListener(CitiesActivity.this);
		// 添加change事件
		mCity.addChangingListener(CitiesActivity.this);
		// 添加change事件
		mArea.addChangingListener(CitiesActivity.this);

		mProvince.setVisibleItems(3);
		mCity.setVisibleItems(3);
		mArea.setVisibleItems(3);
		getIntentData();
	}

	/**
	 * 根据当前的市，更新区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = mCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName).get(pCurrent);
		mCurrentCityId = mCitisDatasMapId.get(mCurrentProviceId).get(pCurrent);
		ArrayList areas = mAreaDatasMap.get(mCurrentCityName);
		if (areas == null) {
			areas = new ArrayList();
		}
		mArea.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
		ArrayList areasId = mAreaDatasMapId.get(mCurrentCityId);
		if ((!TextUtils.isEmpty(mCurrentAreaId)) && areasId.contains(mCurrentAreaId))
			mArea.setCurrentItem(areasId.indexOf(mCurrentAreaId));
		else
			mArea.setCurrentItem(0);
		mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName).get(mArea.getCurrentItem());
		mCurrentAreaId = mAreaDatasMapId.get(mCurrentCityId).get(mArea.getCurrentItem());
	}

	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = mProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas.get(pCurrent);
		mCurrentProviceId = mProvinceDatasId.get(pCurrent);
		ArrayList cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new ArrayList();
		}
		mCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
		ArrayList citiesId = mCitisDatasMapId.get(mCurrentProviceId);
		if ((!TextUtils.isEmpty(mCurrentCityId)) && citiesId.contains(mCurrentCityId))
			mCity.setCurrentItem(citiesId.indexOf(mCurrentCityId));
		else
			mCity.setCurrentItem(0);
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName).get(mCity.getCurrentItem());
		mCurrentCityId = mCitisDatasMapId.get(mCurrentProviceId).get(mCity.getCurrentItem());
	}

//    /**
//     * 根据当前的省，更新市WheelView的信息
//     */
//    private void updateProvince(int pIndex) {
//        int pCurrent = mProvince.getCurrentItem();
//        mCurrentProviceName = mProvinceDatas.get(pCurrent);
//        mCurrentProviceId = mProvinceDatasId.get(pCurrent);
//        ArrayList cities = mCitisDatasMap.get(mCurrentProviceName);
//        if (cities == null) {
//            cities = new ArrayList();
//        }
//        mCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
//        mCity.setCurrentItem(mCurrentCityPos);
//        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName).get(mCurrentCityPos);
//        mCurrentCityId = mCitisDatasMapId.get(mCurrentProviceId).get(mCurrentCityPos);
//        updateAreas();
//    }

	/**
	 * change事件的处理
	 */
	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		if (wheel == mProvince) {
			updateCities();
		} else if (wheel == mCity) {
			updateAreas();
		} else if (wheel == mArea) {
			mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName).get(newValue);
			mCurrentAreaId = mAreaDatasMapId.get(mCurrentCityId).get(newValue);
		}
	}

	public void showChoose(View view) {
		Intent intent = new Intent();
		intent.putExtra("provinceName", mCurrentProviceName);
		intent.putExtra("provinceId", mCurrentProviceId);
		intent.putExtra("cityName", mCurrentCityName);
		intent.putExtra("cityId", mCurrentCityId);
		intent.putExtra("areaName", mCurrentAreaName);
		intent.putExtra("areaId", mCurrentAreaId);
		setResult(RESULT_OK, intent);
		finish();
	}

	public void getIntentData() {
		mCurrentProviceName = getIntent().getStringExtra("provinceName");
		mCurrentProviceId = getIntent().getStringExtra("provinceId");
		mCurrentCityName = getIntent().getStringExtra("cityName");
		mCurrentCityId = getIntent().getStringExtra("cityId");
		mCurrentAreaName = getIntent().getStringExtra("areaName");
		mCurrentAreaId = getIntent().getStringExtra("areaId");
		if (!TextUtils.isEmpty(mCurrentProviceId))
			mProvince.setCurrentItem(Integer.parseInt(mCurrentProviceId) - 1);
		else
			mProvince.setCurrentItem(0);
	}

	public void showClose(View view) {
		finish();
	}

	private String initJsonData() {
		InputStream in = null;
		ByteArrayOutputStream outStream = null;
		try {
			in = getResources().getAssets().open("citys.json");
			outStream = new ByteArrayOutputStream();
			byte[] data = new byte[1024];
			int count = -1;
			while ((count = in.read(data, 0, 1024)) != -1)
				outStream.write(data, 0, count);

			data = null;
			return new String(outStream.toByteArray(), "utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static void buildIntent(Activity context, Intent data, int code) {
		Intent intent = new Intent(context, CitiesActivity.class);
		if (data != null) {
			intent.putExtra("provinceName", data.getStringExtra("provinceName"));
			intent.putExtra("provinceId", data.getStringExtra("provinceId"));
			intent.putExtra("cityName", data.getStringExtra("cityName"));
			intent.putExtra("cityId", data.getStringExtra("cityId"));
			intent.putExtra("areaName", data.getStringExtra("areaName"));
			intent.putExtra("areaId", data.getStringExtra("areaId"));
		}
		context.startActivityForResult(intent, code);
	}

}
